# coding=utf-8
import json
import logging

import time
from django.http import HttpResponse
from django.template import RequestContext

logger = logging.getLogger('django')

class CommonResult:
    def __init__(self, ret, content):
        self.ret = ret
        self.content = content
        self.timestamp = int(time.time())


# 通用装饰器，包装函数返回的dict为通用的返回参数，并json序列化
def rest(func):

    def wrapper(request, *args, **kw):
        start = time.time()
        result = func(request, *args, **kw)
        response = HttpResponse(json.dumps(result, default=serialize), content_type="application/json")
        response["Access-Control-Allow-Origin"] = "*"
        response["Access-Control-Allow-Methods"] = "POST, GET, OPTIONS"
        response["Access-Control-Max-Age"] = "1000"
        response["Access-Control-Allow-Headers"] = "*"
        logger.info("time_consuming = " + str(time.time() - start))
        return response
    return wrapper


def serialize(common_result):
    return {
        "ret": common_result.ret,
        "content": common_result.content,
        "timestamp": common_result.timestamp
    }
